<?php
namespace app\common\business;

use app\common\model\mysql\User as userModel;
use app\common\lib\Str;
use app\common\lib\ExpiresTime;

// 业务逻辑层
class User
{
	public $userObj = null;
	public function __construct(){
		$this->userObj = new userModel();
	}

	// 登录
	public function login($data){
		// 从redis中获取短信验证码
		$redisCode = cache(config('redis.code_pre').$data['phone_number']);
		
		if(empty($redisCode) || $redisCode != $data['code']){
			throw new \think\Exception('不存在该验证码','1001');
		}

		//调用model层获取用户是否存在
		$user = $this->userObj->getUserByPhoneNumber($data['phone_number']);
		//halt($user);
		if(!$user){
			// 如果用户不存在，新增操作
			$userData = [
				"username" => "fresh1204-".$data['phone_number'],
				"phone_number" => $data['phone_number'],
				"type" => $data['type'],
				"status" => config('status.mysql.normal'),
				"create_time" => time(),
			];
			try{
				$this->userObj->save($userData);
				$userId = $this->userObj->id;
				$username = $userData['username'];
			}catch(\Exception $e){
				throw new \think\Exception('数据库内部异常');
			}
		}else{
			// 如果用户存在，更新操作
			$userId = $user->id;
			$username = $user->username;
			$userData = [
				"update_time" => time(),
			];
			try{
				$this->userObj->updateUserByUserId($userId,$userData);
			}catch(\Exception $e){
				throw new \think\Exception('数据库内部异常');
			}
		}

		//获取生成的token
		$token = Str::getLoginToken($data['phone_number']);
		
		$redisData = [
			"id" => $userId,
			"username" => $username,
		];
		// 保存到redis中
		$res = cache(
			config('redis.token_pre').$token,
			$redisData,
			ExpiresTime::userLoginExpiresTime($data['type'])
		);
		
		return $res ? ["token" => $token,"username" => $username] : false;
	}

	// 获取正常用户数据
	public function getNormalUserById($id){
		//调用model层 根据用户id获取用户信息
		$user = $this->userObj->getUserById($id);
		// 判断
		if(!$user || $user->status != config('status.mysql.normal')){
			return [];
		}
		return $user->toArray();
	}

	// 根据用户名获取用户信息
	public function getNormalUserByUsername($username){
		//根据用户名获取用户信息
		$user = $this->userObj->getUserByUserName($username);
		// 判断
		if(!$user || $user->status != config('status.mysql.normal')){
			return [];
		}
		return $user->toArray();
	}

	/**
	 * 更新用户数据
	 */
	public function update($id,$data){
		// 检查该用户是否存在
		$user = $this->getNormalUserById($id);
		//print_r($user);
		if(!$user){
			throw new \think\Exception("不存在该用户", 1);
			
		}
		// 检查用户名是否存在
		$userRes = $this->getNormalUserByUsername($data['username']);
		//由于username字段定义了索引，只能是唯一一个用户名
		if($userRes && $userRes['id'] != $id){
			throw new \think\Exception("该用户已经存在请重新设置", 1);
		}
		return $this->userObj->updateUserByUserId($id,$data);
	}
}